//
//  ViewController.m
//  THiOSWeb
//
//  Created by Dexterlirush on 13-8-26.
//  Copyright (c) 2013年 Dexterlirush. All rights reserved.
//

#import "HomeViewController.h"
#import "NetworkOperation.h"
#import "MenuViewController.h"

#import "NewsViewController.h"
#import "CategorySelectView.h"
#import "UIImageView+AFNetworking.h"
#import "MenuButtonView.h"
#import "SSPullToRefresh.h"


@interface HomeViewController ()
<
CategorySelectViewDelegate, UITableViewDelegate, UITableViewDataSource, NewsTableViewCellDelegate, SSPullToRefreshViewDelegate
>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) CategorySelectView *categorySelectView;
@property (nonatomic, strong) MenuButtonView *menuButton;
@property (nonatomic, strong) NSMutableArray *dataItems;
@property (nonatomic, strong) NSDictionary *requestParameters;
@property (nonatomic, strong) SSPullToRefreshView *pullToRefreshView;
@property (nonatomic) int category;
@property (nonatomic) int currentPages;
@end


@implementation HomeViewController
{
    BOOL menuIsShown;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.category = -1;
    self.currentPages = 1;

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)
    {
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    self.view.frame = CGRectMake(0, 64, 320, CGRectGetHeight([UIScreen mainScreen].bounds) - 64);
    self.tableView = [[UITableView alloc] initWithFrame:[self.view bounds] style:UITableViewStylePlain];
    [self.tableView registerNib:[UINib nibWithNibName:@"NewsTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NewsTableViewCell"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 100;
    
    [self.view addSubview:self.tableView];

    UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [moreButton setBackgroundImage:[UIImage imageNamed:@"Pic1-01.png"] forState:UIControlStateNormal];
    [moreButton setFrame:CGRectMake(0, 0, 23, 20)];
    [moreButton addTarget:self action:@selector(showOrHideMenu) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *moreItem = [[UIBarButtonItem alloc] initWithCustomView:moreButton];
    
    self.menuButton = [[MenuButtonView alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    [self.menuButton addTarget:self action:@selector(showOrHideMenu) forControlEvents:UIControlEventTouchUpInside];
    [self.menuButton setCustomizedTitle:@"精选活动"];
    UIBarButtonItem *menuItem = [[UIBarButtonItem alloc] initWithCustomView:self.menuButton];
    
    [self.navigationItem setLeftBarButtonItems:@[moreItem, menuItem]];
    
    self.navigationItem.rightBarButtonItem = [Util refreshBarButtonItemWithTarget:self selector:@selector(refreshNews)];

    self.categorySelectView = [CategorySelectView categorySelectView];
    self.categorySelectView.delegate = self;
    self.categorySelectView.alpha = 0;
    
    self.pullToRefreshView = [[SSPullToRefreshView alloc] initWithScrollView:self.tableView delegate:self];

    
    [self.view addSubview:self.categorySelectView];
    
    self.requestParameters = [[NSDictionary alloc]initWithObjectsAndKeys:@"0",@"operate",@"3",@"content",[NSString stringWithFormat: @"%i", self.category], @"id",[NSString stringWithFormat: @"%i", self.currentPages], @"page", @"", @"keyword",nil];
    
    [NetworkOperation sendRequestWithHost:@"http://app.student.tsinghua.edu.cn/android" parameters:self.requestParameters completion:^(BOOL success, id error, id info)
     {
         if (success) {
             DebugLog(@"info %@", info);
             self.dataItems = info;
             [self.tableView reloadData];
         }
         else
         {
             DebugLog(@"error: %@", error);
         }
    }];
}

- (void)viewDidUnload
{
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refreshNews
{
    [self pullToRefreshViewDidStartLoading:self.pullToRefreshView];
}

#pragma mark - UITableViewDelegate & DataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataItems count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsTableViewCell *cell = (NewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"NewsTableViewCell"];
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    NSDictionary *news = [self.dataItems objectAtIndex:indexPath.row];
    cell.titleLabel.text = news[@"title"];
    cell.subtitleLabel.text = news[@"date"];
    cell.footage.text = @"2013年5月27日";
    NSString *img = [NSString stringWithFormat:@"http://student.tsinghua.edu.cn%@", news[@"image"]];
    img = [img stringByReplacingOccurrencesOfString:@"&#x2F;" withString:@"/"];
    [cell.imageView setImageWithURL:[NSURL URLWithString:img] placeholderImage:nil];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DebugLog(@"%@", indexPath);
    NewsViewController *news = [[NewsViewController alloc] init];
    id temp = [self.dataItems objectAtIndex:indexPath.row][@"id"];
    news.newsID = [temp intValue];
    [self.navigationController pushViewController:news animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - actions

- (void)showOrHideMenu
{
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    if (menuIsShown == NO) {
        self.categorySelectView.alpha = 0;
        [UIView animateWithDuration:0.2 animations:^{
            self.categorySelectView.alpha = 1;
        }];
    }
    else
    {
        [UIView animateWithDuration:0.3 animations:^{
            self.categorySelectView.alpha = 0;
        }];
    }
    menuIsShown = !menuIsShown;
}


#pragma mark - CategorySelectViewDelegate

- (void)categorySelectView:(CategorySelectView *)categorySelectView didSelectRow:(int)row
{
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView animateWithDuration:0.3 animations:^{
        self.categorySelectView.alpha = 0;
    }];
    menuIsShown = NO;
    
    switch (row) {
        case 1:
            self.category = 0;
            break;
        case 2:
            self.category = -1;
            break;
            
        default:
            self.category = row-1;
            break;
    }
    
    
    NSArray *categories = @[@"全部活动",
                            @"精选活动",
                            @"党团活动",
                            @"体育赛事",
                            @"学术报告",
                            @"文化活动",
                            @"文艺活动",
                            @"其他活动"];
    NSString *title = categories[row];
    [self.menuButton setCustomizedTitle:title];
    
    [self pullToRefreshViewDidStartLoading:self.pullToRefreshView];
}


#pragma mark - SSPullToRefreshViewDelegate

- (BOOL)pullToRefreshViewShouldStartLoading:(SSPullToRefreshView *)view
{
    return YES;
}

- (void)pullToRefreshViewDidStartLoading:(SSPullToRefreshView *)view
{
    // @卢臻 每次下拉的时候去拉取更多的数据，拉取成功之后将数据增加到 self.dataItems
    // 中，然后 reload 表格就可以了。这只是个例子，由于你每次会拉取更老的新闻，所以每次拉取时
    // 请求参数中的起始值要不同。
    
    self.requestParameters = [[NSDictionary alloc]initWithObjectsAndKeys:@"0",@"operate",@"3",@"content",[NSString stringWithFormat: @"%i", self.category], @"id",[NSString stringWithFormat: @"%i", self.currentPages], @"page", @"", @"keyword",nil];
    //[self.requestParameters setValue:[NSString stringWithFormat:@"%i", self.category] forKey:@"id"];
    
    [NetworkOperation sendRequestWithHost:@"http://app.student.tsinghua.edu.cn/android" parameters:self.requestParameters completion:^(BOOL success, id error, id info)
     {
         if (success) {
             DebugLog(@"info %@", info);
             self.dataItems = info;
             [self.tableView reloadData];
         }
         else
         {
             DebugLog(@"error: %@", error);
         }
         [view finishLoading];
     }];
}

- (void)pullToRefreshViewDidFinishLoading:(SSPullToRefreshView *)view
{
    [self.tableView reloadData];
}

- (void)pullToRefreshView:(SSPullToRefreshView *)view didUpdateContentInset:(UIEdgeInsets)contentInset
{
}


@end
